// Copyright (c) 2025 刻BITTER
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.


#include <Arduino.h>
#include <ArduinoJson.h>
#include <FS.h>
#include <LittleFS.h>
#include <Servo.h>
#include <SoftwareSerial.h>
#include <Wire.h>

// scheduler_basic
#include <scheduler_basic.hpp>

// app
#include "app_config.hpp"
#include "image_bitmap.hpp"
#include "io_expansion.hpp"
#include "oled.hpp"
#include "zou.hpp"


// =================== GLOBAL STATIC ==================

// 定时任务调度器，最大16 个任务
scheduler_basic::DelayCallback3<TimeSource, TaskCapacity> delay_callback;

// 默认的RXD 引脚被I2S 占用了，所以用软件串口发送调试信息，只占用TXD 引脚。
// 如果需要双向通讯，考虑用串口引脚重映射
SoftwareSerial serial_log{-1, PIN_TX};


// ==================  Callback TASK  ===================

TimeType task_blink() {
    serial_log.print("TaskCount = ");
    serial_log.print(delay_callback.task_count());
    serial_log.print("\n");
    ex_port2.toggle(EX_P0);
    return 800;
}



// =======================  MAIN  ========================

void setup() {
    // 软串口波特率调高到230400 时会乱码, 115200 偶尔也有乱码
    serial_log.begin(115200);
    Wire.begin(PIN_SDA, PIN_SCL);

    pinMode(PIN_PCF_INT, INPUT_PULLUP);

    init_oled();
    init_servo();
    init_pcf8574();

    delay_callback.add_task(task_blink, 0);
    draw_logo();
}


void loop() {
    delay_callback.tick();

    if(digitalRead(PIN_PCF_INT) == 0) {
        serial_log.println("PCF INT LO");
        
        // 发生中断后，读一次使中断复位
        read_ex1();
        if(test_ex1_pin(EX_BALL)) {
            serial_log.println("BALL HI");
        }
        else {
            serial_log.println("BALL LO");
        }

        if(digitalRead(PIN_PCF_INT) == 0) {
            serial_log.println("PCF INT DONT RESET");
        }
        else {
            serial_log.println("PCF INT RESET");
        }
    }

    delay(300);
}